package test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.model.weixin.AccessToken;
import common.model.weixin.menu.Button;
import common.model.weixin.menu.ClickButton;
import common.model.weixin.menu.Menu;
import common.model.weixin.menu.ViewButton;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Stephen
 */
public class WeixinUtil {
    private static final String APPID = "wx25c8625c4a3ac28a";
    private static final String APPSECRET = "4a7c6a4e947a3176a19ebec7c79f1e2c";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private static final String CREATE_MENU_URL = "http://api.fanyi.baidu.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
    private static final String QUERY_MENU_URL = "http://api.fanyi.baidu.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
    private static final String DELETE_MENU_URL = "http://api.fanyi.baidu.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
    private static HttpClient hc = HttpClients.createDefault();

    /**
     * Get请求
     *
     * @param url
     * @return
     */
    public static JSONObject get(String url/* , List params */) throws IOException {

        // Get请求
        HttpGet httpget = new HttpGet(url);
        // 设置参数
            /*
             * String str = EntityUtils.toString(new
			 * UrlEncodedFormEntity(params)); httpget.setURI(new
			 * URI(httpget.getURI().toString() + "?" + str));
			 */
        // 发送请求
        HttpResponse httpresponse = hc.execute(httpget);
        // 获取返回数据
        HttpEntity entity = httpresponse.getEntity();
        String body = EntityUtils.toString(entity, "utf-8");
        EntityUtils.consume(httpresponse.getEntity());


        return JSON.parseObject(body);
    }

    /**
     * Get请求
     *
     * @param url
     * @return
     */
    public static Object getJavaObject(String url/* , List params */) {
        String body = null;
        try {
            // Get请求
            HttpGet httpget = new HttpGet(url);
            // 设置参数
            /*
             * String str = EntityUtils.toString(new
			 * UrlEncodedFormEntity(params)); httpget.setURI(new
			 * URI(httpget.getURI().toString() + "?" + str));
			 */
            // 发送请求
            HttpResponse httpresponse = hc.execute(httpget);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            //  httpresponse.getEntity().getContent() 可以得到输入流
            body = EntityUtils.toString(entity, "utf-8");

        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return JSON.parse(body);
    }

    /**
     * // Post请求
     *
     * @param url
     * @return
     */
    public static JSONObject post(String url, String param) {

        try {
            // Post请求
            HttpPost httppost = new HttpPost(url);
            httppost.addHeader("Content-Type", "application/octet-stream");
            // 设置参数
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("email", "xxx@gmail.com"));
            params.add(new BasicNameValuePair("pwd", "xxx"));
            params.add(new BasicNameValuePair("save_login", "1"));
            httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
          /*  httppost.setEntity(new StringEntity(param, "UTF-8"));*/
            // post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            // String str = URLEncodedUtils.format(params, "utf-8");
            // 发送请求
            HttpResponse httpresponse = hc.execute(httppost);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            String body = EntityUtils.toString(entity, "utf-8");
            return JSON.parseObject(body);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取accessToken
     *
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static AccessToken getAccessToken() throws IOException {
        String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace(
                "APPSECRET", APPSECRET);
        JSONObject jsonObject = get(url);
        AccessToken token = new AccessToken();
        if (jsonObject != null) {
            token.setToken(jsonObject.getString("access_token"));
            token.setExpiresIn(jsonObject.getIntValue("expires_in"));
        }
        return token;
    }

    /**
     * 组装菜单
     *
     * @return
     */
    public static Menu initMenu() {
        Menu menu = new Menu();
        ClickButton button11 = new ClickButton();
        button11.setName("click菜单");
        button11.setType("click");
        button11.setKey("11");

        ViewButton button21 = new ViewButton();
        button21.setName("view菜单");
        button21.setType("view");
        button21.setUrl("http://user.qzone.qq.com/1051477653/");

        ClickButton button31 = new ClickButton();
        button31.setName("扫码事件");
        button31.setType("scancode_push");
        button31.setKey("31");
        ClickButton button33 = new ClickButton();
        button33.setName("扫码返回");
        button33.setType("scancode_waitmsg");
        button33.setKey("33");
        ClickButton button32 = new ClickButton();
        button32.setName("地理位置");
        button32.setType("location_select");
        button32.setKey("32");

        Button button = new Button();
        button.setName("菜单");
        button.setSub_button(new Button[]{button31, button32, button33});

        menu.setButton(new Button[]{button11, button21, button});
        return menu;
    }

    public static int createMenu(String token, String menu) {
        String url = CREATE_MENU_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = post(url, menu);
        return jsonObject.getIntValue("errcode");

    }

    public static JSONObject queryMenu(String token) throws IOException {
        String url = QUERY_MENU_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = get(url);
        return jsonObject;
    }

    public static int deleteMenu(String token) throws IOException {
        String url = DELETE_MENU_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = get(url);
        return jsonObject.getIntValue("errcode");
    }


    public static String translateFull(String source) throws IOException {
        String url = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id=jNg0LPSBe691Il0CG5MwDupw&q=KEYWORD&from=auto&to=auto";
        try {
            url = url.replace("KEYWORD", URLEncoder.encode(source, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject jsonObject = get(url);
        StringBuffer dst = new StringBuffer();
        List<Map> list = (List<Map>) jsonObject.get("trans_result");
        for (Map map : list) {
            dst.append(map.get("dst"));
        }
        return dst.toString();
    }

    public static void main(String[] args) throws IOException {
        AccessToken at = getAccessToken();
/*		int result = createMenu(at.getToken(), JSON.toJSON(initMenu())
                .toString());*/
        System.out.println("");
        // System.out.println(deleteMenu(at.getToken()));
    }
}
